package com.example.netty.netty.webSocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.time.LocalDate;

//数据类型：文本帧
public class MyTextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        System.out.println("服务器收到消息："+msg.text());
        //回复消息
        ctx.channel().writeAndFlush(new TextWebSocketFrame(LocalDate.now()+"-"+msg.text()));
    }

    //建立连接后，触发该方法
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        //输出channel标识，asLongText是唯一的，asShortText不是唯一的
        System.out.println("handlerAdded方法被调用，"+ctx.channel().id().asLongText()+
                ","+ctx.channel().id().asShortText());
    }

    //断开连接后触发该方法
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handlerRemoved被调用，"+ctx.channel().id().asLongText());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("发生异常："+cause.getMessage());
        ctx.close();
    }
}
